import { inject } from 'vue'
import { showFailToast } from 'vant'
import type { ApplicationIframeSDKManager } from '@/plugins/iframeSDKManager/iframeSDKManager.d'
import { parseTagKeyBord } from '@/utils'
import useSceneDataStore from '@/stores/scene'
import { storeToRefs } from 'pinia'
import type { ProjectInfo } from '@/api/project'

export function useTagManager() {
  const iframeSDKManager = inject('iframeSDKManager') as ApplicationIframeSDKManager
  const sceneDataStore = useSceneDataStore()
  const { currentSceneTagList } = storeToRefs(sceneDataStore)

  // 更新标签标题名称
  const updateBuildingTagNames = async (projectInfo: ProjectInfo) => {
    try {
      // 遍历projectInfo.buildingList，更新每个building的标签名称
      for (const buildingData of projectInfo.buildingList) {
        const buildingId = buildingData.id

        const tagData = currentSceneTagList.value.find((tag: any) => {
          const keybordObject = parseTagKeyBord(tag.keyword) as any
          return keybordObject.type === 'building' && keybordObject.building_id == buildingId
        })

        if (tagData) {
          await iframeSDKManager.setTagTitleText({
            id: tagData.id,
            text: buildingData.name
          })
        }
      }
    } catch (error) {
      showFailToast('更新标签名称失败')

      console.error('更新标签名称失败:', error)
    }
  }

  return {
    updateBuildingTagNames
  }
}
